﻿#include "amplprogram.h"

/**
 * @brief 构造函数
 */
Amplprogram::Amplprogram()
{

}

/**
 * @brief 析构函数
 */
Amplprogram::~Amplprogram()
{}

Q_INVOKABLE   QVariantList Amplprogram::getProgramInfo(QString type)//type:: 0 正常 1 临时 2 打开Open表
{
    QVariantList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql;
    if(type=="0"){
        sql="Select Id,IsDefault,ProgramName,Duration,StepNum,HotCoverStatus,HotCoverTemp,CreateDate,Memo From AmplProgram order by Id ";
    }else if(type=="1"){
        sql="Select Id,IsDefault,ProgramName,Duration,StepNum,HotCoverStatus,HotCoverTemp,CreateDate,Memo From AmplProgramTemp order by Id";
    }else if(type=="2"){
        sql="Select Id,IsDefault,ProgramName,Duration,StepNum,HotCoverStatus,HotCoverTemp,CreateDate,Memo From AmplProgramOpen order by Id";
    }else{
        return result;
    }
    query.exec(sql);
    while (query.next()) {
        QVariantMap map;
        for (int i = 0; i < query.record().count(); ++i) {
            map[query.record().fieldName(i)] = query.value(i);
        }
        result.append(map);
    }
    return  result;
}

Q_INVOKABLE  int Amplprogram::deleteProgramInfo(QString id)//0 成功 1失败
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Delete From AmplStep Where ProgramId='%1'").arg(id);
    bool stepResult = query.exec(sql);

    sql=QString("Delete From AmplProgram Where Id='%1'").arg(id);
    bool programResult = query.exec(sql);

    return  stepResult&&programResult?0:1;
}

Q_INVOKABLE  int Amplprogram::deleteAllProgramInfo()//0 成功 1失败
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Delete From AmplStep";
    bool stepResult = query.exec(sql);

    sql="Delete From AmplProgram";
    bool programResult = query.exec(sql);

    return  stepResult&&programResult?0:1;
}

Q_INVOKABLE  int Amplprogram::setDefaultProgram(QString id,QString defaultType)//0 成功 1失败
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    if(defaultType=="1"){
        QString sql="Update AmplProgram set IsDefault='0'";
        query.exec(sql);
    }
    QString sql=QString("Update AmplProgram set IsDefault='%1' where Id='%2'").arg(defaultType,id);
    return  query.exec(sql)?0:1;
}

Q_INVOKABLE  QVariantList Amplprogram::getProgramStepInfo(QString programId,QString type)//暂时只返步骤
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql;
    QVariantList result;
    if(type=="0"){
        sql=QString("Select Id,StepNum,Temperature,ExecutionTime,Rate,IsCollect,CycleNumber,CycleNum From AmplStep Where ProgramId='%1' order by StepNum ").arg(programId);
    }else if(type=="1"){
        sql=QString("Select Id,StepNum,Temperature,ExecutionTime,Rate,IsCollect,CycleNumber,CycleNum From AmplStepTemp Where ProgramId='%1' order by StepNum ").arg(programId);
    }else if(type=="2"){
        sql=QString("Select Id,StepNum,Temperature,ExecutionTime,Rate,IsCollect,CycleNumber,CycleNum From AmplStepOpen order by StepNum ").arg(programId);
    }else{
        return result;
    }
    query.exec(sql);
    while (query.next()) {
        QVariantMap map;
        for (int i = 0; i < query.record().count(); ++i) {
            map[query.record().fieldName(i)] = query.value(i);
        }
        result.append(map);
    }

    return  result;
}

Q_INVOKABLE QString Amplprogram::saveProgramInfo_open(QVariantMap programInfo,QVariantList stepInfo){

    QSqlDatabase db=dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql;

    QString programId = programInfo["Id"].toString();
    sql = "Delete From AmplStepOpen";
    query.exec(sql);
    sql = "Delete From AmplInfoOpen";
    query.exec(sql);

    foreach(QVariant program,stepInfo){
        QVariantMap map=program.value<QVariantMap>();

        QString StepNum=map.value("StepNum").toString();
        QString temp=map.value("Temperature").toString();
        QString executionTime=map.value("ExecutionTime").toString();
        QString CycleNumber=map.value("CycleNumber").toString();
        QString CycleNum=map.value("CycleNum").toString();
        QString id=map.value("Id").toString();
        QString rate=map.value("Rate").toString();
        QString isCollect=map.value("IsCollect").toString();
        QString sql=QString("Insert or Replace into AmplStepOpen Values('%1','%2','%3','%4',"
                            "'%5','%6','%7','%8','%9')").arg
                (id,programId,StepNum,temp,executionTime,rate,isCollect,CycleNumber,CycleNum);
        query.exec(sql);
    }

    double StepNum=0;
    double CycleNumber=0;
    double CycleNum=0;
    sql=QString("Select StepNum,CycleNumber,CycleNum "
                "From AmplStepOpen "
                "where programId='%1' and "
                "StepNum=(Select max(StepNum) from AmplStepOpen where ProgramId='%1')").arg(programId);

    query.exec(sql);
    while (query.next()) {
        StepNum=query.value("StepNum").toDouble();
        CycleNumber=query.value("CycleNumber").toDouble();
        CycleNum=query.value("CycleNum").toDouble();
    }

    eqptinfo eqInfo;
    QString addNum=eqInfo.calculateDurationread();

    double duration=0;
    sql=QString("Select StepNum,CycleNumber,CycleNum From AmplStepOpen Where ProgramId='%1' and CycleNumber<>0").arg(programId);
    QString stepNumString;

    QList<QString> sqlList;
    query.exec(sql);
    while (query.next())
    {
        for(int i=query.value("CycleNumber").toInt();i<=query.value("StepNum").toInt();i++){
            stepNumString+="'"+QString::number(i)+"',";
        }
        QString sqlInfo=QString("Select sum(ExecutionTime + %4)*%5 as Result from AmplStep where ProgramId='%1' and StepNum between '%2' and'%3'").arg(programId,query.value("CycleNumber").toString(),query.value("StepNum").toString(),addNum,query.value("CycleNum").toString());
        sqlList.append(sqlInfo);
    }
    for(int i=0;i<sqlList.length();i++){
        query.exec(sqlList[i]);
        while (query.next()) {
            duration+=query.value("Result").toDouble();
        }
    }
    stepNumString = stepNumString.left(stepNumString.length()-1);

    sql=QString("Select Sum(ExecutionTime +%3) as Result From AmplStepOpen Where ProgramId='%1' and StepNum not in(%2)").arg(programId,stepNumString,addNum);
    query.exec(sql);
    while (query.next()) {
        duration+=query.value("Result").toDouble();
    }

    QString durationResult;
    if(duration/3600>1){
        double hour=0;
        double min=0;
        double sec=0;

        std::div_t hourResult = std::div(duration, 3600);
        hour=hourResult.quot;

        std::div_t minResult = std::div(duration-hour*3600,60);
        min=minResult.quot;

        sec=duration-hour*3600-min*60;
        durationResult=QString::number(hour)+"时"+QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else if(duration/60>1){
        double min=0;
        double sec=0;
        std::div_t minResult = std::div(duration,60);
        min=minResult.quot;

        sec=duration-min*60;
        durationResult=QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else{
        durationResult=QString::number(duration)+"秒";
    }
    QString dateStr=common->GetDateTimeStr();
    sql=QString("Insert or Replace into AmplProgramOpen values('%1','0','','','','','','%2','');").arg(programId,dateStr);
    query.exec(sql);
    sql=QString("update amplProgramOpen set "
                "programName='%1',"
                "Duration='%3',"
                "StepNum=(Select count(*) from AmplStepOpen where ProgramId='%2'),"
                "Memo='%4',"
                "HotCoverTemp='%5',"
                "HotCoverStatus='%6' "
                "where ID='%2'").arg(programInfo["ProgramName"].toString(),
            programId,durationResult,
            programInfo["Memo"].toString(),programInfo["HotCoverTemp"].toString(),programInfo["HotCoverStatus"].toString());
    query.exec(sql);

    db.commit();

    return "扩增程序信息保存成功";

}

Q_INVOKABLE  QString Amplprogram::saveProgramInfo(QVariantMap programInfo,QVariantList stepInfo)//1.成功 2.校验失败原因
{
    QSqlDatabase db=dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql;

    QString programId = programInfo["Id"].toString();

    db.transaction();

    foreach(QVariant program,stepInfo){
        QVariantMap map=program.value<QVariantMap>();

        QString StepNum=map.value("StepNum").toString();
        QString temp=map.value("Temperature").toString();
        QString executionTime=map.value("ExecutionTime").toString();
        QString CycleNumber=map.value("CycleNumber").toString();
        QString CycleNum=map.value("CycleNum").toString();
        QString id=map.value("Id").toString();
        QString rate=map.value("Rate").toString();
        QString isCollect=map.value("IsCollect").toString();
        QString sql=QString("Insert or Replace into AmplStep Values('%1','%2','%3','%4',"
                            "'%5','%6','%7','%8','%9')").arg
                (id,programId,StepNum,temp,executionTime,rate,isCollect,CycleNumber,CycleNum);
        query.exec(sql);
    }

    double StepNum=0;
    double CycleNumber=0;
    double CycleNum=0;
    sql=QString("Select StepNum,CycleNumber,CycleNum "
                "From AmplStep "
                "where programId='%1' and "
                "StepNum=(Select max(StepNum) from AmplStep where ProgramId='%1')").arg(programId);

    query.exec(sql);
    while (query.next()) {
        StepNum=query.value("StepNum").toDouble();
        CycleNumber=query.value("CycleNumber").toDouble();
        CycleNum=query.value("CycleNum").toDouble();
    }

    eqptinfo eqInfo;
    QString addNum=eqInfo.calculateDurationread();

    double duration=0;
    sql=QString("Select StepNum,CycleNumber,CycleNum From AmplStep Where ProgramId='%1' and CycleNumber<>0").arg(programId);
    QString stepNumString;

    QList<QString> sqlList;
    query.exec(sql);
    while (query.next())
    {
        for(int i=query.value("CycleNumber").toInt();i<=query.value("StepNum").toInt();i++){
            stepNumString+="'"+QString::number(i)+"',";
        }
        QString sqlInfo=QString("Select sum(ExecutionTime + %4)*%5 as Result from AmplStep where ProgramId='%1' and StepNum between '%2' and'%3'").arg(programId,query.value("CycleNumber").toString(),query.value("StepNum").toString(),addNum,query.value("CycleNum").toString());
        sqlList.append(sqlInfo);
    }
    for(int i=0;i<sqlList.length();i++){
        query.exec(sqlList[i]);
        while (query.next()) {
            duration+=query.value("Result").toDouble();
        }
    }
    stepNumString = stepNumString.left(stepNumString.length()-1);

    sql=QString("Select Sum(ExecutionTime +%3) as Result From AmplStep Where ProgramId='%1' and StepNum not in(%2)").arg(programId,stepNumString,addNum);
    query.exec(sql);
    while (query.next()) {
        duration+=query.value("Result").toDouble();
    }

    QString durationResult;
    if(duration/3600>1){
        double hour=0;
        double min=0;
        double sec=0;

        std::div_t hourResult = std::div(duration, 3600);
        hour=hourResult.quot;

        std::div_t minResult = std::div(duration-hour*3600,60);
        min=minResult.quot;

        sec=duration-hour*3600-min*60;
        durationResult=QString::number(hour)+"时"+QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else if(duration/60>1){
        double min=0;
        double sec=0;
        std::div_t minResult = std::div(duration,60);
        min=minResult.quot;

        sec=duration-min*60;
        durationResult=QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else{
        durationResult=QString::number(duration)+"秒";
    }
    QString dateStr=common->GetDateTimeStr();
    sql=QString("Insert or Replace into AmplProgram values('%1','0','','','','','','%2','');").arg(programId,dateStr);
    query.exec(sql);
    sql=QString("update amplProgram set "
                "programName='%1',"
                "Duration='%3',"
                "StepNum=(Select count(*) from AmplStep where ProgramId='%2'),"
                "Memo='%4',"
                "HotCoverTemp='%5',"
                "HotCoverStatus='%6' "
                "where ID='%2'").arg(programInfo["ProgramName"].toString(),
            programId,durationResult,
            programInfo["Memo"].toString(),programInfo["HotCoverTemp"].toString(),programInfo["HotCoverStatus"].toString());
    query.exec(sql);

    db.commit();

    return "扩增程序信息保存成功";

}

Q_INVOKABLE  QString Amplprogram::checkedProgramInfo(QVariantMap programInfo,QVariantList stepInfo){
    QSqlDatabase db=dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql;
    QString programId = programInfo["Id"].toString();

    db.transaction();


    //扩增程序名称校验
    sql=QString("SELECT count(*) as Result From AmplProgram Where ProgramName='%1' and Id<>'%2';").arg(programInfo["ProgramName"].toString(),programId);
    query.exec(sql);
    bool rule = false;
    while (query.next()) {
        rule=query.value("Result").toInt()>0;
    }
    if(rule){
        db.rollback();
        return "程序名称重复,请重新更改程序名称";
    }

    foreach(QVariant program,stepInfo){
        QVariantMap map=program.value<QVariantMap>();

        QString StepNum=map.value("StepNum").toString();
        QString temp=map.value("Temperature").toString();
        QString executionTime=map.value("ExecutionTime").toString();
        QString CycleNumber=map.value("CycleNumber").toString();
        QString CycleNum=map.value("CycleNum").toString();
        QString id=map.value("Id").toString();
        QString rate=map.value("Rate").toString();
        QString isCollect=map.value("IsCollect").toString();
        QString sql=QString("Insert or Replace into AmplStep Values('%1','%2','%3','%4',"
                            "'%5','%6','%7','%8','%9')").arg
                (id,programId,StepNum,temp,executionTime,rate,isCollect,CycleNumber,CycleNum);
        query.exec(sql);
    }

    sql=QString("Select count(*) as num From AmplStep Where ProgramId='%1' and IsCollect='是'").arg(programId);
    query.exec(sql);
    bool collectNumWrong=false;
    while (query.next()) {
        collectNumWrong=query.value("num").toInt()>1;
    }
    if(collectNumWrong){
        db.rollback();
        return  "最多有一个采集数据的步骤";
    }

    //填写内容校验
    sql=QString("SELECT "
                "CASE WHEN CountNum > 1 AND CountRule > 0 "
                "THEN 1 "
                "ELSE 0 END as result "
                "FROM "
                "(SELECT count( * ) CountNum "
                "FROM AmplStep "
                "WHERE programId = '%1' AND Temperature <> '' AND ExecutionTime <> ''),"
                "(SELECT count( * ) CountRule "
                "FROM AmplStep "
                "WHERE programId = '%1' AND Temperature <> '' AND ExecutionTime <> '' AND CycleNumber > 0 AND CycleNum > 1);").arg(programId);
    query.exec(sql);
    rule = false;
    while (query.next()) {
        rule=query.value("Result").toInt()==1;
    }

    if(!rule){
        db.rollback();
        return "至少包含两个步骤，并正确输入温度，时间，循环数信息";
    }

    // 校验是否有多个循环 (JNN)
    sql = QString("select count(*) CycleCount from AmplStep where CycleNumber <> 0 and ProgramId = '%1'").arg(programId);
    query.exec(sql);
    while(query.next()){
        if(query.value("CycleCount").toInt() != 1){
            qDebug() << "步骤数量" << query.value("CycleCount").toInt();
            db.rollback();
            return "扩增程序只能有一个扩增步骤";
        }
    }

    db.rollback();
    return "校验成功";
}
